import React, { useState } from 'react';
import styles from './index.module.less';
import ApproveCard from '@/components/card';
import { DeleteDoc, GetDraftList } from '@/services/official-doc';
import { SwipeAction, Toast } from 'antd-mobile-v2';
import FilterArea, { OptionsListItem } from '@/components/filter-area';
import moment from 'moment';
import { SecondConfirm } from '@/components/second-confirm';
import { DraftListItem } from './interface';
import { DRAFT_QUERY_TYPE } from '../../official-doc/constants';
import { draftTypeMap } from '@/constants';
import history from '@/utils/history';
import AntdRefreshList from '@/components/antd-refresh-list';
import EmptyRefresh from '@/components/empty/empty-refresh';
import EmptyLoading from '@/components/empty/empty-loading';
import { DelRucDraft } from '@/services/laber-declare';
import { Prompt } from 'react-router-dom';
import { PrintNum } from '@/utils';
import { useRefreshList } from '@/hooks/use-refresh-list';
import { applyType } from '@/constants';

const filterData: OptionsListItem[] = [
  {
    label: '类型',
    value: 'type',
    options: [
      { label: '全部', value: '' },
      {
        label: '申报',
        value: `${DRAFT_QUERY_TYPE.DECLARE_STUDENT},${DRAFT_QUERY_TYPE.DECLARE_OUTSCHOOL},${DRAFT_QUERY_TYPE.DECLARE_INOTHER}`
      }
    ]
  },
  {
    label: '时间',
    value: 'time',
    options: [
      { label: '全部', value: '' },
      { label: '近3天', value: 3 },
      { label: '近7天', value: 7 },
      { label: '近30天', value: 30 }
    ]
  }
];

const height =
  document.documentElement.clientHeight -
  (document.documentElement.clientWidth * 11) / 100;

const DraftList: React.FC<RouterProps> = (props) => {
  const defaultPageSize = 10;

  const [pageSize, setPageSize] = useState(defaultPageSize);

  const {
    showDom,
    refreshing,
    loadingMore,
    dataSource,
    searchData,
    setDatasource,
    handleRefresh,
    handleLoadMore,
    handleSearch,
    routeWillLeave
  } = useRefreshList({
    routeProps: props,
    cacheRouteList: [
      '/official-doc/detail',
      '/declare/detail',
      '/official-doc/edit',
      '/resubmit'
    ],
    pullData: async (options) => {
      const { params, setLastId, setSurplusTotal, setData } = options;
      const reqParams = {
        lastId: params.lastId,
        pageNum: params?.pageNum || 1,
        pageSize: params?.pageNum
          ? PrintNum(params?.pageNum * defaultPageSize)
          : defaultPageSize,
        typeList: parseArr(params?.type),
        startDate: params?.time && formatTime(params?.time)
      };
      const res = await GetDraftList(reqParams);
      const list = formatData(res.data?.list || []) || [];
      const surplusTotal = res.data?.total - list.length; // 加载完当前请求的数据还剩多少条数据
      setSurplusTotal(surplusTotal < 0 ? 0 : surplusTotal);
      setPageSize(
        params?.pageNum
          ? PrintNum(params?.pageNum * defaultPageSize)
          : defaultPageSize
      );
      setData(params?.lastId ? dataSource.concat(list) : list);
      setLastId(list[list.length - 1]?.id);
    }
  });

  const formatData = (data: any[]): any => {
    data?.forEach((item) => {
      switch (item.applyType) {
        case applyType.STOCK_RECEIVE_APPLY:
          item.formData = [
            { label: '划转批次', value: item.lot?.text || '无' },
            {
              label: '业务名称',
              value: item.typeName || item.taskName || '无'
            },
            {
              label: '更新时间',
              value: item?.lastHandlerTime || item.crtTime || '无'
            }
          ];
          break;
        default:
          break;
      }
      item.cardTitle = item.applyName || item.procName || '无';
    });
    return data;
  };

  const formatTime = (day: number) => {
    return moment()
      .set({ hour: 0, minute: 0, second: 0 })
      .subtract(day, 'days')
      .format('YYYY-MM-DD HH:mm:ss');
  };

  // number和string类型的参数转数组
  const parseArr = (data: number | string | undefined) => {
    if (!data) return undefined;
    if (typeof data === 'number') {
      data = data.toString();
    }
    return data.split(',').map((item) => Number(item));
  };

  const handleDelete = async (item) => {
    // 线下公文独立的删除接口
    let res;
    if (item.type === DRAFT_QUERY_TYPE.OFFICIAL_OFFLINE) {
      res = await DeleteDoc(item.bizId);
    } else {
      res = await DelRucDraft(item?.bizId);
    }
    if (res.status === 200) {
      Toast.info('删除成功');
      setDatasource(dataSource.filter((it) => it?.bizId !== item?.bizId)); // 删除列表数据，不重新请求列表
    }
  };

  const handleCardClick = (item: DraftListItem) => {
    console.log(item.type);
    history.push({
      pathname: '/declare/detail',
      query: {
        applyType: draftTypeMap[item.type],
        innerProcDefId: item.innerProcDefId,
        applyId: item.bizId || item.id,
        status: 0,
        title: item.draftTitle
      }
    });

    // switch (item.type) {
    //   case DRAFT_QUERY_TYPE.DECLARE_STUDENT:
    //   case DRAFT_QUERY_TYPE.OFFICIAL_ONLINE:
    //   case DRAFT_QUERY_TYPE.DECLARE_OUTSCHOOL:
    //   case DRAFT_QUERY_TYPE.DECLARE_INOTHER:
    //     history.push({
    //       pathname: '/declare/detail',
    //       query: {
    //         applyType: draftTypeMap[item.type],
    //         innerProcDefId: item.innerProcDefId,
    //         applyId: item.bizId || item.id,
    //         status: 0,
    //         title: item.draftTitle,
    //       },
    //     });
    //     break;
    //   default:
    //     break;
    // }
  };

  const handleCard2Edit = (item) => {
    // 除线下公文外，都进申报详情页
    if (item.type === DRAFT_QUERY_TYPE.OFFICIAL_OFFLINE) {
      props.history.push(`/official-doc/edit/${item.bizId}?entry=draft`);
    } else {
      history?.push({
        pathname: '/resubmit',
        query: {
          applyType: draftTypeMap[item.type],
          applyId: item.bizId,
          innerProcDefId: item.innerProcDefId,
          status: 0,
          resubmit: false,
          title: item.draftTitle,
          entry: 'draft'
        }
      });
    }
  };

  const rightBtns = (itemInfo: { bizId: string; type: number }) => {
    return [
      {
        text: '修改',
        onPress: () => handleCard2Edit(itemInfo),
        style: {
          backgroundColor: '#C7C7CC',
          color: 'white',
          fontSize: '18px',
          padding: '7px'
        }
      },
      {
        text: '删除',
        style: {
          backgroundColor: '#FF3A30',
          color: 'white',
          fontSize: '18px',
          padding: '7px'
        },
        onPress: () => {
          const params = {
            buttons: [
              {
                text: '删除',
                cb: () => handleDelete(itemInfo)
              },
              {
                text: '取消'
              }
            ],
            message: '确认删除？'
          };
          SecondConfirm(params);
        }
      }
    ].filter((item) => item);
  };

  return (
    <div>
      <FilterArea
        data={filterData}
        values={searchData}
        onFilterChange={handleSearch}
      />
      {showDom ? (
        <div className={styles.cardList}>
          {dataSource?.length > 0 ? (
            <AntdRefreshList
              height={height}
              initialListSize={pageSize}
              dataSource={dataSource}
              refreshing={refreshing}
              loadingMore={loadingMore}
              renderRow={(item, sectionID, index) => (
                <div className={styles.cardItem} key={index}>
                  <SwipeAction right={rightBtns(item)}>
                    <div onClick={() => handleCardClick(item)}>
                      <ApproveCard data={item} hasAvatar></ApproveCard>
                    </div>
                  </SwipeAction>
                </div>
              )}
              onRefresh={handleRefresh}
              onEndReached={handleLoadMore}
            />
          ) : (
            <EmptyRefresh
              refreshing={refreshing}
              onRefresh={handleRefresh}
              emptyProps={{ text: '暂无草稿' }}
            />
          )}
        </div>
      ) : (
        <EmptyLoading />
      )}
      <Prompt message={routeWillLeave} />
    </div>
  );
};

export default DraftList;
